<!-- eslint-disable no-unused-vars -->
<!-- eslint-disable no-unused-vars -->
<template>
  <div class="home">
    <div>
      <el-button type="primary" @click="onLink">全部连线</el-button>
      <el-button @click="onCancelLink">取消连线</el-button>
    </div>
    <div id="container"></div>
  </div>
</template>

<script>
import { Graph } from '@antv/x6'
import { register } from '@antv/x6-vue-shape';
import CustomNode from './Custom.vue';
import { 
  titleArr, 
  dataList, 
  width, 
  height, 
  cWidth, 
  titleHeight, 
  compWidth, 
  compHeight,
} from './constant'

export default {
  components: {
  },
  data() {
    return {
      titleArr,
      dataList,
      edges: [],
      nodes: [],
      allNodes: [],
      graph: null,
    }
  },
  mounted() {
    const container = document.getElementById("container");
    console.log(container.getBoundingClientRect())
    
    this.graph = new Graph({
      container: container,
      width: width,
      height: height,
      // autoResize: true, // 自动适应外部容器大小
      interacting: { // 限制所有节点的交互
        nodeMovable: false, // 禁用节点移动
        edgeMovable: false, // 禁用边移动
        magnetConnectable: false, // 当在具有 'magnet' 属性的元素上按下鼠标开始拖动时，是否触发连线交互。
        edgeMovable: false, // 边是否可以被移动。
        edgeLabelMovable: false, // 边的标签是否可以被移动。
        arrowheadMovable: false, // 边的起始/终止箭头是否可以被移动。
        vertexMovable: false, // 边的路径点是否可以被移动。
        vertexAddable: false, // 是否可以添加边的路径点。
        vertexDeletable: false, // 边的路径点是否可以被删除
      }, 
      connecting: { // 当 snap 设置为 true 或者 false 代表开启和关闭连线过程中自动吸附
        router: "orth",
      },
      // 保持节点在父容器内移动
      translating: {
        restrict(cellView) {
          const { cell } = cellView;
          const parentId = cell.prop("parent");
          if (parentId) {
            const parentNode = this.graph.getCellById(parentId);
            if (parentNode) {
              return parentNode.getBBox().moveAndExpand({
                x: 0,
                y: 30, // 节点在父容器内可移动的范围
                width: 0,
                height: -30,
              });
            }
          }
          return cell.getBBox();
        },
      },
    });

    // 容器
    Graph.registerNode(
      "lane",
      {
        inherit: "rect",
        markup: [
          {
            tagName: "rect",
            selector: "body",
          },
          {
            tagName: "rect",
            selector: "name-rect",
          },
          {
            tagName: "text",
            selector: "name-text",
          },
        ],
        attrs: {
          body: {
            fill: "#FFF",
            stroke: "#5F95FF",
            strokeWidth: 1,
          },
          "name-rect": {
            width: cWidth, // 表头宽度
            height: titleHeight, // 表头高度
            fill: "skyblue",
            stroke: "#fff",
            strokeWidth: 1,
            x: -1,
          },
          "name-text": {
            ref: "name-rect",
            refY: 0.5,
            refX: 0.5,
            textAnchor: "middle",
            fontWeight: "bold",
            fill: "blue",
            fontSize: 12,
          },
        },
      },
      true,
    );

    // 注册自定义节点
    register({
      shape: 'lane-rect',
      width: compWidth,
      height: compHeight,
      component: CustomNode,
      // ports: {
      //   groups: {
      //     top: {
      //       position: 'top',
      //       attrs: {
      //         circle: {
      //           r: 4,
      //           magnet: true,
      //           stroke: '#C2C8D5',
      //           strokeWidth: 1,
      //           fill: '#fff',
      //         },
      //       },
      //     },
      //     bottom: {
      //       position: 'bottom',
      //       attrs: {
      //         circle: {
      //           r: 4,
      //           magnet: true,
      //           stroke: '#C2C8D5',
      //           strokeWidth: 1,
      //           fill: '#fff',
      //         },
      //       },
      //     },
      //   },
      // },
    })

    // 边
    Graph.registerEdge(
      "lane-edge",
      {
        inherit: "edge",
        router: {
          name: "normal", // 直线连接
          // args: {
          //   startDirections: ['left'],
          //   endDirections: ['right'],
          // },
        },
        // connector: { name: "rounded" },
        attrs: {
          line: {
            targetMarker: "classic",
            stroke: "#faad14",
          },
        },
        label: {
          attrs: {
            label: {
              fill: "#A2B1C3",
              fontSize: 12,
            },
          },
        },
      },
      true,
    );

    // 内容高度
    const contentHeight = height - titleHeight;
    function handler(arr) {
      const nodes = [];
      const edges = [];
      const obj = {};
      arr.forEach((item, index) => {
        const currentObj = titleArr.find((he) => item.type === he.id);
        const node = {
          // 节点
          shape: "lane-rect",
          name: item.name,
          id: item.code,
          label: item.name,
          parent: currentObj.id, // 所在节点位置
          // width: 30, // 节点宽
          // height: 30, // 节点高
          position: {
            // 节点所在位置
            x: currentObj.position.x + 50,
            // y: (index + 1) * 50,
          },
          ports: {
            groups: {
              group1: {
                attrs: {
                  circle: {
                    r: 1,
                    magnet: false, // 是否启用手动桩连线
                    stroke: "#31d0c6",
                    fill: "red",
                    strokeWidth: 5,
                  },
                },
                position: {
                  name: "absolute",
                },
              },
            },
            items: [
              {
                id: "left",
                group: "group1",
                // 通过 args 指定绝对位置
                args: {
                  x: '38%',
                  y: "35%",
                },
              },
              {
                id: "right",
                group: "group1",
                // 通过 args 指定绝对位置
                args: {
                  x: "62%",
                  y: "35%",
                },
              },
            ],
          },
        };
        nodes.push(node);
        if (item.source.length) {
          item.source.forEach((el, index) => {
            edges.push({
              // 边
              shape: "lane-edge",
              // tools: [
              //   {
              //     name: "edge-editor", // 开启双击边可编辑
              //     args: {
              //       attrs: {
              //         backgroundColor: "#fff",
              //       },
              //     },
              //   },
              // ],
              name: index,
              target: {
                cell: el,
                port: "right",
              },
              source: {
                cell: item.code,
                port: "left",
              },
            });
          });
        }
        if (obj[item.type]) {
          obj[item.type].push(node);
        } else {
          obj[item.type] = [node];
        }
      });
      console.log('obj', obj);
      Object.keys(obj).forEach((item) => {
        const itemLength = obj[item].length;
        let iH = 0;
        if (itemLength === 1) {
          iH = contentHeight / 2;
        } else {
          iH = contentHeight / (itemLength); // 计算出每一个块的高度
        }
        console.log('iH', iH);
        obj[item].forEach((el, index) => {
          el.position.y = (iH ) * (index + 1) - compHeight;
        });
      });

      return {
        nodes,
        edges,
      };
    }
    const { nodes, edges } = handler(dataList);
    this.edges = edges;
    this.nodes = nodes;
    this.allNodes = [...titleArr, ...nodes];

    this.graph.on("node:click", (obj) => {
      console.log("点击了节点", edges, obj, obj.node.store.previous.data);
      const findEdges = edges.filter((item) => item.source.cell === obj.node.id);
      console.log('找到的边', findEdges);
      const allEdge = this.graph.getEdges();
      console.log('获取所有的边', allEdge);
      findEdges.forEach((edge) => {
        const edgeInstances = allEdge.filter((item) => item.source.cell === edge.source.cell);
        console.log('匹配的边', edgeInstances);
        if (!edgeInstances.length) {
          this.graph.addEdge(edge)
        } else {
          // 已添加的边来删除
          edgeInstances.forEach((e) => {
            e.remove();
          })
        }
      })
      // this.graph.trigger('render')
    });
    

    const cells = [];
    this.allNodes.forEach((item, index) => {
      if (item.shape === "lane-edge") {
        this.graph.addEdge(item)
        // cells.push(graph.createEdge(item));
      } else {
        console.log('item', item);
        const node = this.graph.addNode({
          data: { 
            name: item.name,
            type: item.parent,
          },
          ...item,
        })
        // 传递数据
        // setTimeout(() => {
        //   node.setData({
        //     name: 'hhh',
        //     label: '高级数据'
        //   })
        // }, 0)
        // cells.push(this.graph.createNode(item));
      }
    });
    // this.graph.resetCells(cells);
    // this.graph.zoomToFit({ padding: 10, maxScale: 1 });
    console.log('所有节点', this.graph.getNodes())
  },
  methods: {
    onCancelLink() {
      const allEdge = this.graph.getEdges();
      allEdge.forEach((item) => {
        item.remove();
      })
    },
    onLink() {
      this.edges.forEach((edge) => {
        this.graph.addEdge(edge)
      })
    }
  }
};
</script>

<style >
.home {
  width: 1000px; 
  height: 1000px;
  margin-left: 50px; 
  background-color: #ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}
#container {
  margin-top: 20px;
}
</style>
